/*
 * Copyright (C) 2010 Yury Kudryashov.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package name.kudryashov.concurrent;

import name.kudryashov.base.Argument;
import name.kudryashov.functions.Procedure;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class NotifyingSyncVar<T> {

    private final SyncVar<T> var;
    private final List<Procedure<NotifyingSyncVar<T>>> listeners = new CopyOnWriteArrayList<Procedure<NotifyingSyncVar<T>>>();

    public NotifyingSyncVar(T ref) {
        var = new SyncVar<T>(ref);
    }

    public NotifyingSyncVar() {
        var = new SyncVar<T>();
    }

    public T get() throws InterruptedException {
        return var.get();
    }

    public void set(T value) {
        var.set(value);
        for(Procedure<NotifyingSyncVar<T>> p : listeners) {
            p.call(this);
        }
    }

    public void unset() {
        var.unset();
    }

    public void addListener(Procedure<NotifyingSyncVar<T>> listener) {
        listeners.add(Argument.requireNotNull(listener, "listener"));
    }

    public void removeListener(Procedure<NotifyingSyncVar<T>> listener) {
        listeners.remove(Argument.requireNotNull(listener, "listener"));
    }
}
